// 调用js浮层
var pageAdminAdd = null;
$('#k_add').live(
		'click',
		function() {
			pageAdminAdd = $.layer({
				type : 1,
				title : false,
				area : [ '580', 'auto' ],
				border : [ 0 ],
				shade : [ 0.3, '#000' ],
				closeBtn : [ 0, false ],
				fadeIn : 500,
				move : ".key_layer .tit",
				page : {
					dom : '.key_layer'
				}
			});
			// 自设关闭
			$('.key_layer > .closeBtn,.key_layer .cancelLayer').live('click',function() {
				layer.close(pageAdminAdd);
				$(".clearFormInput").val("");
				$(".clearFormDiv").text("");
				document.getElementById("orgImageAddText").value = document.getElementById("e_file").value = '';
			});
			avoidDup = true;
			$('#addParameterArea').validationEngine('validate');
		});

var pageAdminUpdate = null;
$('.revise').live(
		'click',
		function() {
			pageAdminUpdate = $.layer({
				type : 1,
				title : false,
				area : [ '580', 'auto' ],
				border : [ 0 ],
				shade : [ 0.3, '#000' ],
				closeBtn : [ 0, false ],
				fadeIn : 500,
				move : ".key_layerEdit .tit",
				page : {
					dom : '.key_layerEdit'
				}
			});

			// 自设关闭
			$('.key_layerEdit > .closeBtn,.key_layerEdit .cancelLayer').live('click', function() {
				layer.close(pageAdminUpdate);
				document.getElementById("orgImageEditText").value = document.getElementById("e_file").value = '';
			});

			var orgName = $(this).attr("orgName").trim();
			$("#orgNameEditText").val(orgName);

			var groupId = $(this).attr("groupId").trim();
			$("#adminUpdateId").val(groupId);

			var orgShort = $(this).attr("orgShort").trim();
			$("#orgShortEditText").val(orgShort);

			var groupSketch = $(this).attr("groupSketch");
			$("#orgEditDesc").text(groupSketch);

			var groupImage = $(this).attr("groupImage")||'';
			$("#orgImageTextHidden").val(groupImage);
//			$("#orgImageEditText").val(groupImage);
						
			var hasIfmCount = $(this).attr("hasIfmCount");
			$("#hasIfmCountEdit").val(hasIfmCount);

			var hasUserCount = $(this).attr("hasUserCount");
			$("#hasUserCountEdit").val(hasUserCount);
		});

var q = {
	// 采集预警
	"loadData" : function(data) {
		var objCount = data.returnData.length; // 取得组织管理列表
		window.curLen = objCount;
		var htmlList = "", oldOrgImage = "";
		var basePath =data.basePath;
		for (var i = 0; i < objCount; i++) {
			var orgName = data.returnData[i].groupName;
			var orgImage = data.returnData[i].groupImage;
			var orgShort = data.returnData[i].groupBrie;
			var groupId = data.returnData[i].groupId;
			var groupSketch = data.returnData[i].groupSketch;
			var hasIfmCount = data.returnData[i].schemeNum;
			var hasUserCount = data.returnData[i].userNum;
			var rptRight = data.returnData[i].rptRight;
			var modelcount = data.returnData[i].modelcount;
			//地址
			if (rptRight == 0) {
				var rptRightText = '开启';
			} else {
				var rptRightText = '关闭';
			}
			var ifmlName = "", ifmlId = new Array();
			var ifml = data.returnData[i].ifmInfoName.split(',');
			for (var j = 0; j < ifml.length; j++) {
				var ifmll = ifml[j].split('|');
				ifmlName = ifmlName + ifmll[0];
				if (j < ifml.length - 1) {
					ifmlName += ",";
				}
				ifmlId[j] = ifmll[1];
			}
			var ifm_id = ifmlId.join(",");

			var ifmlmg = data.returnData[i].ifmInfoId;
			if (ifmlmg != "") {
				ifmlmgArr = ifmlmg.split('|');
				ifmsId = ifmlmgArr[1];
			} else {
				ifmsId = "";
			}
			oldOrgImage = orgImage;
			if (orgImage == "" || orgImage == null) {
				orgImage = "/HandleAdmin/images/DefaultAvatar.png";
			}else{
				orgImage=basePath+orgImage;
			}
			if(oldOrgImage){
				var oldOrgImageStr = ' groupImage=' + oldOrgImage;
			}else{
				var oldOrgImageStr = "";
			}
			htmlList = htmlList
					+ '<tr class="td">'
					+ '<td class="tl"><img  width="65" height="65" src='
					+ orgImage
					+ '>'
					+ '</td><td><span title='
					+ orgName
					+ '>'
					+ orgName
					+ '</span></td><td><span title='
					+ orgShort
					+ '>'
					+ orgShort
					+ '</span></td><td colspan="3"><span title='
					+ ifmlName
					+ '>'
					+ ifmlName
					+ '</span></td><td colspan="1"><a href="javascript:void(0);" data-url="orgPramEdit.jsp?orgName='
					+ encodeURIComponent(orgName)
					+ '&groupId='
					+ groupId
					+ '&ifmlId='
					+ ifm_id
					+ '&ifmsId='
					+ ifmsId
					+ '&ifmlName='
					+ encodeURIComponent(ifmlName)
					+ '" class="green openF">编辑</a></td><td><a href="javascript:void(0);" onclick="modifyBtn('
					+ groupId
					+ ','
					+ rptRight
					+ ')">'
					+ rptRightText
					+ '</a></td><td><a href="javascript:void(0);" class="revise" groupId='
					+ groupId + ' orgName=' + orgName + ' orgShort=' + orgShort
					+ ' hasIfmCount=' + hasIfmCount + ' hasUserCount='
					+ hasUserCount 
					+ oldOrgImageStr
					+ ' groupSketch=' + groupSketch
					+ ' >修改</a><a href="javascript:void(0);" orgName='
					+ orgName + ' groupId=' + groupId + ' modelcount='
					+ modelcount + ' class="removeBtn">删除</a></td></tr>';
		}
		var strHead = "<tr class='th'><th width='120' height='50'>组织图片</th><th width='200'>组织名称</th><th width='200'>组织简称</th><th width='400' colspan='4'>信息方案权限</th><th width='100'>报告权限</th><th>操作</th></tr>";
		var strPage = "<tr class='pages'><td colspan='9'><div class='ui_page' id='pageArea'></div></td></tr>";
		if (objCount < 1) {
			$(".ktab")
					.html(
							strHead
									+ "<tr class='td' colspan='9'>加载失败，请刷新重试！<td></td></tr>");
		} else {
			$(".ktab").html(strHead + htmlList + strPage);
		}
	},
	// public load ajax
	"publicAjax" : function(pIndex, numList, selectJson) {
		var url = basePath + "group/select.do?pageIndex=" + pIndex
				+ "&pageSize=" + numList + '&vtimes=' + new Date().getTime();
		var _obj = $(".ktab");
		$
				.ajax({
					type : "POST",
					url : url,
					data : selectJson,
					error : function(request) {
						layer.msg("加载失败，请刷新重试！", 2, -1);
					},
					success : function(data) {
						if (data.returnCode == 10000) {
							if (data.returnData != null
									&& data.returnData.length != 0) {
								q.loadData(data);
								paging.loadPage(data);
							} else if (data.returnData == null
									|| data.returnData.length == 0) {
								$(".ktab")
										.html(
												"<tr class='th'><th width='120' height='50'>组织图片</th><th width='200'>组织名称</th><th width='200'>组织简称</th><th width='400' colspan='4'>信息方案权限</th><th width='100'>报告权限</th><th>操作</th></tr><tr class='td'><td colspan='9'>很遗憾，没有查询到相关数据！</td></tr>");
							}
						} else if (data.returnCode == 999994) {
							setUserTimeout(data);
						}
					},
					beforeSend : function() {
						var imgGif = "<p class='loadingGif'></p>";
						_obj.html(imgGif);
					}
				});
	}
}

function modifyBtn(id, isOpen) {
	if (id != undefined) {
		$.layer({
			title : "温馨提示：",
			shade : [ 0 ],
			area : [ '230', 'auto' ],
			dialog : {
				msg : '确定' + (isOpen == 0 ? "开启报告权限吗？" : "关闭报告权限吗？"),
				btns : 2,
				type : -1,
				btn : [ '确定', '取消' ],
				yes : function() {
					var params = {
						groupId : id,
						rptRight : isOpen
					};
					// 0--表示目前为关闭状态，点击按钮后请求开启，所以赋值为1，再发送。
					if (params.rptRight == 0) {
						params.rptRight = 1;
					} else {
						params.rptRight = 0;
					}
					$.post(basePath + 'group/updateByGroupId.do', params)
							.success(function(data) {
								layer.msg(data.returnMessage, 1, 10);
								setTimeout(function() {
									$(".pNumBtn .cur").trigger('click');
								}, 800);
							});
				},
				no : function() {
				}
			}
		});
	}
}

// 页面初始化
q.publicAjax(1, numList, selectJsonData);

// 点击查询
$("#selectAll").live("click", function() {
	curPage = 1;
	qDataFun(curPage);
});
$('.enterSearch').keydown(function(e) {
	if (e.keyCode == 13) {
		curPage = 1;
		qDataFun(1);
	}
});
// 点击触发换页的按钮
$("#pageArea .pNumBtn  a").live("click", function() {
	curPage = parseInt($(this).attr("toPage"));
	qDataFun(curPage);
});

// 点击触发分批显示的按钮
$("#pageArea .columnsPage a").live("click", function() {
	numList = parseInt($(this).text());
	curPage = 1;
	qDataFun(curPage);
	subPage = $(this).index();
});
// 跳转
$("#pageArea .gopg .btn").live("click", function() {
	curPage = parseInt($("#pageArea .gopg .txt").val());
	// 判断输入的页数是否大于最大的页数
	if (curPage > countPage) {
		curPage = countPage;
	}
	if (curPage > 0) {
		qDataFun(curPage);
	}
});

function qDataFun(curPages) {
	orgName = $("#orgNameSearch").val();
	orgShort = $("#orgShortSearch").val();
	selectJsonData = null;
	selectJsonData = {
		groupName : orgName,
		groupBrie : orgShort,
	};
	q.publicAjax(curPages, numList, selectJsonData);
};

// 点击新增
$("#addParameterArea").validationEngine({
	"focusFirstField" : true,
	"maxErrorsPerField" : "1"
});
var avoidDup = true;
$("#addParameterBtn").live("click", function() {
	if (avoidDup == false) {
		return false;
	}
	var isSuccess = $('#addParameterArea').validationEngine('validate');
	if (isSuccess == true) {
		var fpath = document.getElementById("a_file").value;
		if(fpath){
			var fsize = document.getElementById("a_file").files[0].size,
				maxsize = 2*1024*1024;
			if(!/\.(bmp|jpg|jpeg|png|BMP|JPG|JPEG|PNG)$/.test(fpath)){
				 layer.msg("图片仅限于jpg、jpeg、png、bmp格式！",2,5);
				 return false;
			}else if(fsize>maxsize){
				 layer.msg("图片的大小不能超过2M！",2,5);
				 return false;
			}
		}
		avoidDup = false;
		add.sava();
	}
});

var add = {
	sava : function() {
		var orgName = $("#orgNameText").val();
		var orgShort = $("#orgShortText").val();
		var orgDesc = $("#orgDesc").text();
		var hasIfmCount = $("#hasIfmCount").val();
		var hasUserCount = $("#hasUserCount").val();
		var formData = new FormData();
		formData.append("groupName", orgName);
		formData.append("groupBrie", orgShort);
		formData.append("groupSketch", orgDesc);
		formData.append("schemeNum", hasIfmCount);
		formData.append("userNum", hasUserCount);
		formData.append("file", $("#a_file")[0].files[0]);

		var url = basePath + "group/addGroup";
		$.ajax({
			type : "POST",
			url : url,
			data : formData,
			processData : false,
			contentType : false,
			error : function(request) {
				layer.msg("操作失败，请刷新重试！", 2, -1);
			},
			success : function(data) {
				if (data.returnCode == 10000) {
					layer.msg(data.returnMessage, 2, 10);
					setTimeout(function() {
						try {
							$('#selectAll').trigger('click');
						} catch (e) {
						}
					}, 1000);
					layer.close(pageAdminAdd);
					// q.publicAjax(1, numList, "");
					$(".clearFormInput").val("");
					$(".clearFormDiv").text("");
					document.getElementById("orgImageAddText").value = document.getElementById("e_file").value = '';

				} else if (data.returnCode == 999994) {
					setUserTimeout(data);
				} else {
					layer.msg(data.returnMessage, 2, -1);
					avoidDup = true;
				}
			}
		});
	}
};

// 信息方案编辑事件
$("#editParameterArea").validationEngine({
	"focusFirstField" : true,
	"maxErrorsPerField" : "1"
});
$("#updateParameterBtn").live("click", function() {
	var isSuccess = $('#editParameterArea').validationEngine('validate');
	if (isSuccess == true) {
		if($("#orgImageEditText").val()){
			var fpath = document.getElementById("e_file").value,
				fsize = document.getElementById("e_file").files[0].size,
				maxsize = 2*1024*1024;
			if(!/\.(bmp|jpg|jpeg|png|BMP|JPG|JPEG|PNG)$/.test(fpath)){
				 layer.msg("图片仅限于jpg、jpeg、png、bmp格式！",2,5);
				 return false;
			}else if(fsize>maxsize){
				 layer.msg("图片的大小不能超过2M！",2,5);
				 return false;
			}
		}
		edit.postRightEditAjax();
	}
});

var edit = {
	"editRightFrom" : function() {
		var orgName = $("#orgNameEditText").val();
		var orgShort = $("#orgShortEditText").val();
		var orgImage = $("#orgImageTextHidden").val();
		var orgDesc = $("#orgEditDesc").text();
		id = $("#adminUpdateId").val();
		var hasIfmCountEdit = $("#hasIfmCountEdit").val();
		var hasUserCountEdit = $("#hasUserCountEdit").val();
		var formData = new FormData();
		formData.append("groupName", orgName);
		formData.append("groupBrie", orgShort);
		formData.append("groupSketch", orgDesc);
		formData.append("groupImage", orgImage);
		formData.append("groupId", id);
		formData.append("schemeNum", hasIfmCountEdit);
		formData.append("userNum", hasUserCountEdit);
		formData.append("file", $("#e_file")[0].files[0]);
		return formData;
	},
	// 权限修改接口
	"postRightEditAjax" : function() {
		var url = basePath + "group/modifyGroup";
		$.ajax({
			type : 'POST',
			url : url,
			processData : false,
			contentType : false,
			data : edit.editRightFrom(),
			success : function(data) {
				if (data.returnCode == 10000) {
					layer.msg(data.returnMessage, 1, 10);
					layer.close(pageAdminUpdate);
					document.getElementById("orgImageEditText").value = document.getElementById("e_file").value = '';
					q.publicAjax(curPage, numList, selectJsonData);
				} else if (data.returnCode == 999994) {
					setUserTimeout(data);
				} else {
					layer.msg(data.returnMessage, 2, -1);
				}
			},
			error : function(message) {
				layer.msg(message, 2, -1);
			}
		});
	},
};

// 点击删除
$(".removeBtn").live("click", function() {
	var orgId = $(this).attr("groupId").trim();
	var orgName = $(this).attr("orgName").trim();
	if ($(this).attr("modelcount") > 0) {
		var msg = "删除组织，关联的用户及报告模板会自动删除，请确认？";
	} else {
		var msg = "删除组织，关联的用户会自动删除，请确认？";
	}
	$.layer({
		title : "温馨提示：",
		shade : [ 0 ],
		area : [ '230', 'auto' ],
		dialog : {
			msg : msg,
			btns : 2,
			type : -1,
			btn : [ '确定', '取消' ],
			yes : function() {
				removes.removeAjax(orgId, orgName);
			},
			no : function() {
			}
		}
	});
});
var removes = {
	"removeAjax" : function(orgid, orgname) {
		var url = basePath + 'group/delGroup';
		$.ajax({
			type : 'GET',
			url : url,
			data : {
				"groupId" : orgid,
				"groupName" : orgname
			},
			success : function(data) {
				if (data.returnCode == 10000) {
					layer.msg(data.returnMessage, 1, 10);
					if (window.curLen == 1 && curPage > 1) {
						curPage = curPage - 1;
					}
					q.publicAjax(curPage, numList, selectJsonData);
				} else if (data.returnCode == 999994) {
					setUserTimeout(data);
				} else {
					layer.msg(data.returnMessage, 1, -1);
				}
			},
			error : function(message) {
				layer.msg("删除数据失败！<br>" + message, 2, -1);
			}
		});
	}
}